<?php

namespace app\admin\controller;

use app\common\controller\AdminController;

//引入外部函数
use app\common\model\hfztcy\LibAdminWithdrawalApply;
use app\common\model\hfztcy\LibAdminBalanceChangeRecords;
use app\common\model\hfztcy\LibConfig;
use app\common\model\hfztcy\LibVideoAuth;
use app\common\model\hfztcy\LibVip;
use app\common\model\LibAdmin;
use common\Common;
use think\Db;
use think\Exception;


/**
 * 配置
 * @name Config.php
 * @package hfztcy
 * @category controller
 * @author rxy
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2020-6-5
 */
class Config extends AdminController
{
    protected $lib_config;

    protected $configInfo = [];

    protected $fields = [];

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->lib_config = new LibConfig();
        $this->rightVerify(session('admin'), url("admin/Login/login"));
        if (!$this->configInfo) {
            $configInfo = $this->lib_config->findAllConfig();
            $data = [];
            foreach ($configInfo['data'] as $item) $data[$item['item_key']] = $item['item_value'];
            // vip收费模式
            if (isset($data['vip_model_rate'])) $data['vip_model_rate'] = json_decode($data['vip_model_rate'], true);
            // 单次付费看视频
            if (isset($data['see_video_rate'])) $data['see_video_rate'] = json_decode($data['see_video_rate'], true);
            // 视频认证收费
            if (isset($data['vip_video_auth_rate'])) $data['vip_video_auth_rate'] = json_decode($data['vip_video_auth_rate'], true);
            // 红娘认证收费
            if (isset($data['red_mother_auth_rate'])) $data['red_mother_auth_rate'] = json_decode($data['red_mother_auth_rate'], true);
            $this->configInfo = $data;
        }

        $this->fields = [
            'system' => ['about_us', 'guide', 'vip_contents', 'privacy_agreement',  'user_agreement',  'marriage_agreement', 'withdrawal_lines', 'withdrawal_service_fee', 'direct_register_member_count', 'direct_red_mother_count', 'promote_contents', 'posters_img', 'category_posters_img', 'red_mother_posters_img', 'platform_mobile', 'evaluate_content','short_video'],
            'vipUser' => ['vip_contents', 'vip_auth_fee', 'vip_auth_introduce'],
            'redMother' => ['matchmaker_introduce', 'matchmaker_auth_fee', 'matchmaker_auth_introduce', 'matchmaker_pic'],
            'stores' => ['stores_introduce', 'stores_auth_introduce', 'stores_pic'],
            'videoAuth' => ['title','money','content','agreement']
        ];
        parent::__construct();
    }

    /**
     * Info: vip套餐-配置
     * Date: 2022/8/24 15:36
     */
    function vipPackageConfig()
    {
        $this->getSetMenu($this);
        $model = new LibVip();
        $vipMonthList = $model->findVip(['type' => 0]);
        $vipSeasonList = $model->findVip(['type' => 1]);
        $vipYearList = $model->findVip(['type' => 2]);
        $this->assign('vipMonth', $vipMonthList['data']);
        $this->assign('vipSeason', $vipSeasonList['data']);
        $this->assign('vipYear', $vipYearList['data']);
        $this->log(__CLASS__, __FUNCTION__, "vip套餐-配置页面", 1, 'view');
        return $this->fetch('Config/vipPackageConfig/vipPackageConfig');
    }

    /**
     * Info: 系统管理-配置
     * Date: 2022/8/24 15:36
     */
    function systemConfig()
    {
        $this->getSetMenu($this);
        $this->assign('configInfo', $this->configInfo);
        $this->log(__CLASS__, __FUNCTION__, "系统管理-配置页面", 1, 'view');
        return $this->fetch('Config/systemConfig/systemConfig');
    }

    /**
     * Info: vip用户管理-配置
     * Date: 2022/8/24 15:36
     */
    function vipUserConfig()
    {
        $this->getSetMenu($this);
        $this->assign('configInfo', $this->configInfo);
        $this->log(__CLASS__, __FUNCTION__, "vip用户管理-配置页面", 1, 'view');
        return $this->fetch('Config/vipUserConfig/vipUserConfig');
    }

    /**
     * Info: 红娘-配置
     * Date: 2022/8/24 15:36
     */
    function redMotherConfig()
    {
        $this->getSetMenu($this);
        $this->assign('configInfo', $this->configInfo);
        $this->log(__CLASS__, __FUNCTION__, "红娘-配置页面", 1, 'view');
        return $this->fetch('Config/redMotherConfig/redMotherConfig');
    }

    /**
     * Info: 门店-配置
     * Date: 2022/8/24 15:36
     */
    function storesConfig()
    {
        $this->getSetMenu($this);
        $this->assign('configInfo', $this->configInfo);
        $this->log(__CLASS__, __FUNCTION__, "门店-配置页面", 1, 'view');
        return $this->fetch('Config/storeConfig/storeConfig');
    }

    /**
     * Info: 红娘-配置
     * Date: 2022/8/24 15:36
     */
    function videoAuthConfig()
    {
        $this->getSetMenu($this);
        $model = new LibVideoAuth();
        $findPackageOneRes = $model->findVideoAuth(['type' => 1]);
        $findPackageTwoRes = $model->findVideoAuth(['type' => 2]);
        $findPackageThreeRes = $model->findVideoAuth(['type' => 3]);
        $this->assign('packageOneInfo', $findPackageOneRes['data']);
        $this->assign('packageTwoInfo', $findPackageTwoRes['data']);
        $this->assign('packageThreeInfo', $findPackageThreeRes['data']);
        $this->log(__CLASS__, __FUNCTION__, "视频认证-配置页面", 1, 'view');
        return $this->fetch('Config/videoAuthConfig/videoAuthConfig');
    }

    /**
     * Info: 提现-账号
     * Date: 2022/8/24 15:36
     */
    function adminWithdrawalAccountConfig()
    {
        $this->getSetMenu($this);
        $admin_id = session('admin.id');
        $model = new LibAdmin();
        $findRes = $model->findAdmin(['id' => $admin_id]);
        $this->assign('adminInfo', $findRes['data']);
        $this->assign('configInfo', json_decode($findRes['data']['business_name'], true));
        $this->log(__CLASS__, __FUNCTION__, "提现-账号页面", 1, 'view');
        return $this->fetch('Config/adminWithdrawalAccountConfig/adminWithdrawalAccountConfig');
    }

    /**
     * Info: 提现-账号
     * Date: 2022/8/24 15:36
     */
    function adminStaffWithdrawalConfig()
    {
        $this->getSetMenu($this);
        $admin_id = session('admin.id');
        $model = new LibAdmin();
        $findRes = $model->findAdmin(['id' => $admin_id]);
        $this->assign('adminInfo', $findRes['data']);
        $this->assign('configInfo', json_decode($findRes['data']['business_name'], true));
        $this->log(__CLASS__, __FUNCTION__, "提现-账号页面", 1, 'view');
        return $this->fetch('Config/adminStaffWithdrawalConfig/adminStaffWithdrawalConfig');
    }

    /**
     * Info: 更新
     * Date: 2022/8/24 15:36
     */
    function updateConfig()
    {
        $fields = $this->fields;
        $type = input('type', '');
        if (isset($fields[$type])) {
            $args = $this->getArgsList($fields[$type], false);
            $matchmaker_pic_flag = input('matchmaker_pic_flag');
            $stores_pic_flag = input('stores_pic_flag');
            $posters_img_flag = input('posters_img_flag');
            $category_posters_img_flag = input('category_posters_img_flag');
            $red_mother_posters_img_flag = input('red_mother_posters_img_flag');
            $short_video_flag = input('short_video_flag');
            if ($matchmaker_pic_flag == '1') {
                //上传红娘图
                $uploadResult = $this->lib_config->uploadMatchmakerImg();
                if ($uploadResult['errorCode'] == 0) {
                    $result = $this->lib_config->findConfig(['item_key' => 'matchmaker_pic']);
                    if ($result['errorCode'] == 0 && $result['data']['item_value']) unlink(ROOT_PATH . 'public/' . $result['data']['item_value']);
                    $args['matchmaker_pic'] = $uploadResult['data']['path'];
                } elseif ($uploadResult['errorCode'] == 1) {
                    echo json_encode(Common::errorArray(1, $uploadResult['errorInfo'], []));
                    die;
                }
            }
            if ($stores_pic_flag == '1') {
                //上传店铺图
                $uploadResult = $this->lib_config->uploadStoreImg();
                if ($uploadResult['errorCode'] == 0) {
                    $result = $this->lib_config->findConfig(['item_key' => 'stores_pic']);
                    if ($result['errorCode'] == 0 && $result['data']['item_value']) unlink(ROOT_PATH . 'public/' . $result['data']['item_value']);
                    $args['stores_pic'] = $uploadResult['data']['path'];
                } elseif ($uploadResult['errorCode'] == 1) {
                    echo json_encode(Common::errorArray(1, $uploadResult['errorInfo'], []));
                    die;
                }
            }
            if ($posters_img_flag == '1') {
                //上传海报图
                $uploadResult = $this->lib_config->uploadPosterImg();
                if ($uploadResult['errorCode'] == 0) {
                    $configRes = $this->lib_config->findConfig(['item_key' => 'posters_img']);
                    if ($configRes['errorCode'] == 0 && $configRes['data']['item_value']) @unlink(ROOT_PATH . 'public/' . $configRes['data']['item_value']);
                    $args['posters_img'] = $uploadResult['data']['path'];
                } elseif ($uploadResult['errorCode'] == 1) {
                    echo json_encode(Common::errorArray(1, $uploadResult['errorInfo'], []));
                    die;
                }
            }
            if ($category_posters_img_flag == '1') {
                //上传栏目视频背景图
                $uploadResult = $this->lib_config->uploadCategoryPosterImg();
                if ($uploadResult['errorCode'] == 0) {
                    $configRes = $this->lib_config->findConfig(['item_key' => 'category_posters_img']);
                    if ($configRes['errorCode'] == 0 && $configRes['data']['item_value']) @unlink(ROOT_PATH . 'public/' . $configRes['data']['item_value']);
                    $args['category_posters_img'] = $uploadResult['data']['path'];
                } elseif ($uploadResult['errorCode'] == 1) {
                    echo json_encode(Common::errorArray(1, $uploadResult['errorInfo'], []));
                    die;
                }
            }
            if ($red_mother_posters_img_flag == '1') {
                //上传红娘视频背景图
                $uploadResult = $this->lib_config->uploadRedMotherPosterImg();
                if ($uploadResult['errorCode'] == 0) {
                    $configRes = $this->lib_config->findConfig(['item_key' => 'red_mother_posters_img']);
                    if ($configRes['errorCode'] == 0 && $configRes['data']['item_value']) @unlink(ROOT_PATH . 'public/' . $configRes['data']['item_value']);
                    $args['red_mother_posters_img'] = $uploadResult['data']['path'];
                } elseif ($uploadResult['errorCode'] == 1) {
                    echo json_encode(Common::errorArray(1, $uploadResult['errorInfo'], []));
                    die;
                }
            }
            if ($short_video_flag == '1') {
                $uploadResult = $this->lib_config->uploadVideo();
                if ($uploadResult['errorCode'] == 0) {
                    $configRes = $this->lib_config->findConfig(['item_key' => 'short_video']);
                    if ($configRes['errorCode'] == 0 && $configRes['data']['item_value']) @unlink(ROOT_PATH . 'public/' . $configRes['data']['item_value']);
                    $args['short_video'] = $uploadResult['data']['path'];
                } elseif ($uploadResult['errorCode'] == 1) {
                    echo json_encode(Common::errorArray(1, $uploadResult['errorInfo'], []));
                    die;
                }
            }

            // VIP分销比例
            if (isset($_POST['vip_model_rate'])) {
                $vip_model_rate = $_POST['vip_model_rate'];
                $vip_model_rate_total = array_values($vip_model_rate);
                if (array_sum($vip_model_rate_total) > 1) {
                    echo json_encode(Common::errorArray(1, 'VIP分销比例大于100%', true));
                    die();
                }
                $args['vip_model_rate'] = json_encode($vip_model_rate, JSON_UNESCAPED_UNICODE);
            }
            // 单次付费看视频分销比例
            if (isset($_POST['see_video_rate'])) {
                $see_video_rate = $_POST['see_video_rate'];
                $see_video_rate_total = array_values($see_video_rate);
                if (array_sum($see_video_rate_total) > 1) {
                    echo json_encode(Common::errorArray(1, '单次付费看视频分销比例大于100%', true));
                    die();
                }
                $args['see_video_rate'] = json_encode($see_video_rate, JSON_UNESCAPED_UNICODE);
            }
            // 视频认证收费
            if (isset($_POST['vip_video_auth_rate'])) {
                $vip_video_auth_rate = $_POST['vip_video_auth_rate'];
                $vip_video_auth_rate_total = array_values($vip_video_auth_rate);
                unset($vip_video_auth_rate_total[0], $vip_video_auth_rate_total[1]);
                if (array_sum($vip_video_auth_rate_total) > 1) {
                    echo json_encode(Common::errorArray(1, '视频认证收费分销比例大于100%', true));
                    die();
                }
                $args['vip_video_auth_rate'] = json_encode($vip_video_auth_rate, JSON_UNESCAPED_UNICODE);
            }
            // 红娘认证收费
            if (isset($_POST['red_mother_auth_rate'])) {
                $red_mother_auth_rate = $_POST['red_mother_auth_rate'];
                $red_mother_auth_rate_total = array_values($red_mother_auth_rate);
                unset($red_mother_auth_rate_total[0], $red_mother_auth_rate_total[1]);
                if (array_sum($red_mother_auth_rate_total) > 1) {
                    echo json_encode(Common::errorArray(1, '红娘认证收费分销比例大于100%', true));
                    die();
                }
                $args['red_mother_auth_rate'] = json_encode($red_mother_auth_rate, JSON_UNESCAPED_UNICODE);
            }
        } else {
            $args = [];
        }

        if ($args) {
            foreach ($args as $key => $value) {
                $result = $this->lib_config->findConfig(['item_key' => $key]);
                if ($result['errorCode'] == 0) {
                    $this->lib_config->updateConfig(['id' => $result['data']['id']], ['item_key' => $key, 'item_value' => $value]);
                } else {
                    $this->lib_config->addConfig(['item_key' => $key, 'item_value' => $value]);
                }
            }
        }
        echo json_encode(Common::errorArray(0, '保存成功', true));
        die();
    }

    /**
     * Info: 保存vip套餐
     * Date: 2022/8/24 15:36
     */
    function saveVipPackageConfig()
    {
        $input = $_POST['vip_package'];
        $model = new LibVip();
        foreach ($input as $item) {
            $res = $model->findVip(['type' => $item['type']]);
            if ($res['errorCode'] == 0) {
                $model->updateVip(['type' => $item['type']], $item);
            } else {
                $model->addVip($item);
            }
        }
        echo json_encode(Common::errorArray(0, '保存成功', true));
        die();
    }

    /**
     * Info: 保存视频认证套餐
     * Date: 2022/8/24 15:36
     */
    function saveVideoAuthConfig()
    {
        $input = $_POST['video_auth'];
        $model = new LibVideoAuth();
        foreach ($input as $item) {
            $res = $model->findVideoAuth(['type' => $item['type']]);
            if ($res['errorCode'] == 0) {
                $model->updateVideoAuth(['type' => $item['type']], $item);
            } else {
                $model->addVideoAuth($item);
            }
        }
        echo json_encode(Common::errorArray(0, '保存成功', true));
        die();
    }

    /**
     * Info: 保存代理商提现账号
     * Date: 2022/11/14 16:26
     */
    function saveAgentWithdrawalAccount()
    {
        $input = $_POST['form'];
        $admin_id = session('admin.id');
        $model = new LibAdmin();
        $findRes = $model->findAdmin(['id' => $admin_id]);
        if ($findRes['errorCode'] == 0) {
            $model->updateAdmin(['id' => $admin_id], ['business_name' => json_encode($input, JSON_UNESCAPED_UNICODE)]);
        }
        echo json_encode(Common::errorArray(0, '保存成功', true));
        die();
    }

    /**
     * Info: 保存员工提现账号
     * Date: 2022/11/14 16:26
     */
    function saveStaffWithdrawalAccount()
    {
        $input = $_POST['form'];
        $admin_id = session('admin.id');
        $model = new LibAdmin();
        $findRes = $model->findAdmin(['id' => $admin_id]);
        if ($findRes['errorCode'] == 0) {
            $model->updateAdmin(['id' => $admin_id], ['business_name' => json_encode($input, JSON_UNESCAPED_UNICODE)]);
        }
        echo json_encode(Common::errorArray(0, '保存成功', true));
        die();
    }

    /**
     * Info: 我要提现【代理商】【客服部】【培训部】【员工】
     * Date: 2022/11/14 18:21
     */
    function myWithdrawalBalance()
    {
        $money = input('money', 0);
        if (empty($money)) {
            echo json_encode(Common::errorArray(1, '提现金额不能为空', false));
            die();
        }

        $admin_id = session('admin.id');
        $adminModel = new LibAdmin();
        $findRes = $adminModel->findAdmin(['id' => $admin_id]);
        if ($findRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1, '管理员不存在', false));
            die();
        }

        $balance = (float)$findRes['data']['balance'];
        $money = (float)$money;
        if ($balance < $money) {
            echo json_encode(Common::errorArray(1, '提现金额超出用户余额', false));
            die();
        }

        if (empty($findRes['data']['business_name'])) {
            echo json_encode(Common::errorArray(1, '请设置提现账号', false));
            die();
        }

        $configModel = new LibConfig();
        $findConfigRes = $configModel->findConfig(['item_key' => 'withdrawal_lines']);
        $minWithdrawalMoney = 0;
        if ($findConfigRes['errorCode'] == 0) {
            $minWithdrawalMoney = (float)$findConfigRes['data']['item_value'];
        }
        if ($money < $minWithdrawalMoney) {
            echo json_encode(Common::errorArray(1, '提现金额不足' . $findConfigRes['data']['item_value'] . '，不允许提现。', false));
            die();
        }

        Db::startTrans();
        try {
            // 添加提现申请
            $data = [];
            $data['user_id'] = $admin_id;
            $data['account_info'] = $findRes['data']['business_name'];
            $data['amount'] = $money;
            $data['add_time'] = Common::getTime();
            $model = new LibAdminWithdrawalApply();
            $model->addWithdrawalApply($data);

            // 余额变动记录
            $data = [];
            $data['user_id'] = $admin_id;
            $data['before_balance'] = $findRes['data']['balance'];
            $data['amount'] = $money;
            $data['add_time'] = Common::getTime();
            $data['is_income'] = 1;
            $balanceChangeModel = new LibAdminBalanceChangeRecords();
            $balanceChangeModel->addBalanceChangeRecords($data);

            // 扣除用户余额
            $adminModel->decreaseField(['id' => $admin_id], 'balance', $money);
            // 放入冻结字段
            $adminModel->updateAdmin(['id' => $admin_id], ['freeze_balance' => $money]);

            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
        }
        echo json_encode(Common::errorArray(0, '提现申请已提交，等待平台审核', false));
        die();
    }
}

?>